package com.distribution.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.distribution.common.core.redis.RedisCache;
import com.distribution.common.utils.StringUtils;
import com.distribution.common.utils.spring.SpringUtils;
import com.distribution.system.domain.entity.CmccDaOrder;
import com.distribution.system.domain.entity.CmccDaProduct;
import com.distribution.system.domain.req.ReqResult;
import com.distribution.system.service.AliSmsSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: GodLu
 * @create: 2024-04-28 14:10
 * @description: 阿里短信验证服务
 */
@Service
@Slf4j
public class AliSmsSendServiceImpl implements AliSmsSendService {
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.endpoint}")
    private String endpoint;

    @Value("${aliyun.sms.signName}")
    private String signName;

    //模板代码
    @Value("${aliyun.sms.smsTemplateCode}")
    private String smsTemplateCode;

    //模板代码
    @Value("${aliyun.sms.commissionListenTemplateCode}")
    private String commissionListenTemplateCode;

    @Resource
    RedisCache redisCache;

    /**
     * @Author: GodLu
     * @Date: 2025/1/18 14:03
     * @Description: 生成并发送验证码
     * @param phoneNum 接收验证码的手机号
     * @param redisKey 缓存键
     * @return: ReqResult
     */
    public ReqResult genAndSendAliSmsCode(String phoneNum, String redisKey){
        // 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // redis缓存，有效时间5分钟
        redisCache.setCacheObject(redisKey, code, 5, TimeUnit.MINUTES);
        //  发送验证码
        if (sendSms(phoneNum, code)){// 成功
            return ReqResult.success("验证码发送成功");
        } else {// 失败
            return ReqResult.error("验证码发送失败");
        }
    }

    /**
     * @Author: GodLu
     * @Date: 2024/7/16 11:53
     * @Description: 校验短信验证码
     * @param verifyCode 要验证的验证码
     * @param redisKey 缓存键
     * @return: ReqResult
     */
    public ReqResult verifySmsCode(String verifyCode, String redisKey){
        String code = redisCache.getCacheObject(redisKey);
        if (StringUtils.isEmpty(code)){// 验证码失效
            return ReqResult.error("验证码已失效");
        }
        if (!StringUtils.equals(verifyCode, code)){// 验证失败
            return ReqResult.error("验证码错误");
        }
        // 验证成功后从缓存中移除
        redisCache.deleteObject(redisKey);
        return ReqResult.success("验证成功");
    }

    public boolean sendSms(String phoneNumber,String code) {
        JSONObject codeJson = new JSONObject();
        codeJson.put("code",code);
        ReqResult reqResult = sendMessage(smsTemplateCode, phoneNumber, codeJson);
        return reqResult.getCode() == 200;
    }

    public void sendCommissionDepreciate(String phoneNumber, JSONObject paramJson) {
        sendMessage(commissionListenTemplateCode, phoneNumber, paramJson);
    }

    public ReqResult sendMessage(String templateCode, String phoneNumber, JSONObject paramJson) {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = endpoint;
        try {
            com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setPhoneNumbers(phoneNumber)
                    .setTemplateParam(paramJson.toString());
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            log.info("短信发送结果：{} | {}", sendSmsResponse.getBody().code, sendSmsResponse.getBody().message);
            return StringUtils.equals("OK",sendSmsResponse.getBody().code) ? ReqResult.success("发送成功") : ReqResult.error(sendSmsResponse.getBody().message);
        } catch (TeaException error) {
            log.error("发送失败，{}",error.getMessage());
            return ReqResult.error("发送失败，" + error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            log.error("发送失败，{}",error.getMessage());
            return ReqResult.error("发送失败，" + error.getMessage());
        }
    }
}
